package com.mingtu.guards.activity;

import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.exoplayer2.SeekParameters;
import com.gyf.immersionbar.ImmersionBar;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.basic.PictureMediaScannerConnection;
import com.luck.picture.lib.dialog.PictureLoadingDialog;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.core.BottomPopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.util.XPopupUtils;
import com.lxj.xpopup.widget.VerticalRecyclerView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.StatusBarUtil;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.VideoSubAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.share.BottomPopupShare2;
import com.mob.MobSDK;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener;
import com.shuyu.gsyvideoplayer.listener.LockClickListener;
import com.shuyu.gsyvideoplayer.model.GSYVideoModel;
import com.shuyu.gsyvideoplayer.model.VideoOptionModel;
import com.shuyu.gsyvideoplayer.utils.GSYVideoType;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.ListGSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.wechat.favorite.WechatFavorite;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import tv.danmaku.ijk.media.exo2.Exo2PlayerManager;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

public class VideoPlayActivity extends MyBaseActivity {


    @BindView(R.id.status_bar_view)
    View statusBarView;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.iv_multi)
    ImageView ivMulti;
    private OrientationUtils orientationUtils;
    private boolean isPlay;
    private boolean isPause;
    private String videoRecordUrl;
    private String title;
    private final String TAG = "video";
    private ListGSYVideoPlayer videoPlayer;
    private String savePath = PathUtils.getExternalMoviesPath();
    private PictureLoadingDialog mLoadingDialog;
    private DownloadTask downloadTask;
    private List<String> numberList;
    private BasePopupView popupView;
    private String[] arrayUrl;
    private VideoSubAdapter videoSubAdapter;
    private List<GSYVideoModel> urls = new ArrayList<>();
    private int position = 0;
    private String videoUrl;
    private BasePopupView popupViewShare;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_video_play;
    }

    @Override
    protected void initView() {
        hideHeadView();
        StatusBarUtil.addStatusBarHeight(statusBarView);
        ImmersionBar immersionBar = ImmersionBar.with(this);
        immersionBar.statusBarDarkFont(false);
        immersionBar.init();
        videoPlayer = findViewById(R.id.video_player);
        videoPlayer.getBackButton().setVisibility(View.GONE);
        videoPlayer.getFullscreenButton().setOnClickListener(new FullScreenOnClickListener());
    }

    @Override
    protected void initData() {
        videoRecordUrl = getIntent().getStringExtra("vodeoUrl");
        title = getIntent().getStringExtra("title");
        boolean shareFlag = getIntent().getBooleanExtra("shareFlag", false);
        if (!StringUtils.isEmpty(title)) {
            tvTitle.setText(title);
        }
        if (shareFlag) {
            ivMore.setVisibility(View.VISIBLE);
        } else {
            ivMore.setVisibility(View.GONE);
        }
    }

    @Override
    protected void getData() {
        if (StringUtils.isEmpty(videoRecordUrl)) {
            ToastUtils.showLong("抱歉，未获取到直播链接哦~");
            return;
        }

        if (videoRecordUrl.indexOf(",") != -1) { //多段视频
            ivMulti.setVisibility(View.VISIBLE);
            arrayUrl = videoRecordUrl.split(",");
            numberList = new ArrayList<>();
            for (int i = 0; i < arrayUrl.length; i++) {
                urls.add(new GSYVideoModel(arrayUrl[i], title));
                numberList.add("视频" + (i + 1));
            }

        } else {
            ivMulti.setVisibility(View.GONE);
            arrayUrl = new String[1]; //为了保持下载逻辑一直，此处创建一个长度为1的数组
            arrayUrl[0] = videoRecordUrl;
            urls.add(new GSYVideoModel(videoRecordUrl, title));
        }


        playVideo(urls, position); //此处的positon == 0
    }

    @Override
    protected void onPause() {
        super.onPause();
        getCurPlay().onVideoPause();
        isPause = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        getCurPlay().onVideoResume(false);
        isPause = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (isPlay) {
            getCurPlay().release();
        }
//        GSYPreViewManager.instance().releaseMediaPlayer();
        GSYVideoManager.releaseAllVideos();

        if (orientationUtils != null) {
            orientationUtils.releaseListener();
        }

        if (downloadTask != null) {
            downloadTask.unRegister(videoUrl); //监听取消,避免造成泄漏
        }

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        MyLogUtil.e("video", "onConfigurationChanged");
        //如果旋转了就全屏 容易出现闪屏，隐藏
//        if (isPlay && !isPause) {
//            videoPlayer.onConfigurationChanged(this, newConfig, orientationUtils, false, false);
//        }

        if (popupView != null) {
            popupView.dismiss();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        if (orientationUtils != null) {
            orientationUtils.backToProtVideo();
        }
        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }

    @OnClick({R.id.iv_back, R.id.iv_more, R.id.iv_multi})
    public void onViewClicked(View view) {

        videoUrl = arrayUrl[position];
        //好友
        String content = "绿水青山就是金山银山";
        Bitmap imageData = MyUtills.drawable2Bitmap(context.getResources().getDrawable(R.drawable.bg_shared_img));
        final OnekeyShare oks = new OnekeyShare();
        oks.setText(title + "视频");
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(content);
        oks.setTitleUrl("https://www.mingtukeji.com");
        // text是分享文本，所有平台都需要这个字段
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
//                        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setImageData(imageData);
        oks.setVideoUrl(videoUrl);

        switch (view.getId()) {
            case R.id.iv_back:
                ActivityUtil.removeActivity(this);
                break;
            case R.id.iv_more:
//                if (layoutShare.getVisibility() == View.VISIBLE) {
//                    hideShareUI();
//                } else {
//                    showShareUI();
//                }

                //分享
                BottomPopupShare2 bottomPopup = new BottomPopupShare2(this);
                bottomPopup.setOnItemClickListener(new BottomPopupShare2.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        popupViewShare.dismiss();
                        switch (position) {
                            case 0:
                                oks.setPlatform(Wechat.NAME);
                                oks.show(MobSDK.getContext());
                                break;
                            case 1:
                                oks.setPlatform(WechatMoments.NAME);
                                oks.show(MobSDK.getContext());
                                break;
                            case 2:
                                oks.setPlatform(WechatFavorite.NAME);
                                oks.show(MobSDK.getContext());
                                break;
                            case 3:
                                XXPermissions.with(VideoPlayActivity.this)
                                        // 不适配 Android 11 可以这样写
                                        .permission(Permission.Group.STORAGE)
                                        // 适配 Android 11 需要这样写，这里无需再写 Permission.Group.STORAGE
//                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                                        .request(new OnPermissionCallback() {
                                            @Override
                                            public void onGranted(List<String> permissions, boolean all) {
                                                if (permissions.contains(Permission.WRITE_EXTERNAL_STORAGE) || permissions.contains(Permission.READ_EXTERNAL_STORAGE)) {
                                                    downVideo();
                                                }
                                            }

                                            @Override
                                            public void onDenied(List<String> permissions, boolean never) {
                                                if (never) {
                                                    // 如果是被永久拒绝就跳转到应用权限系统设置页面
                                                    new XPopup.Builder(VideoPlayActivity.this)
                                                            .isDestroyOnDismiss(true)
                                                            .dismissOnTouchOutside(true)
                                                            .hasShadowBg(true)
                                                            .asConfirm(context.getResources().getString(R.string.text_tip), context.getResources().getString(R.string.text_storage_auth),
                                                                    context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                                                    new OnConfirmListener() {
                                                                        @Override
                                                                        public void onConfirm() {
                                                                            XXPermissions.startPermissionActivity(VideoPlayActivity.this, permissions);
                                                                        }
                                                                    }, null, false)
                                                            .show();
                                                }
                                            }
                                        });

                                break;
                        }
                    }
                });
                popupViewShare = new XPopup.Builder(this)
                        .navigationBarColor(getResources().getColor(R.color.white))
                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                        .asCustom(bottomPopup)
                        .show();


                break;

            case R.id.iv_multi:
                popupView = new XPopup.Builder(this)
                        .moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面
                        .enableDrag(true)
                        .isDarkTheme(true)
                        .navigationBarColor(getResources().getColor(R.color.black))
                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
//                        .isThreeDrag(true) //是否开启三阶拖拽，如果设置enableDrag(false)则无效
                        .asCustom(new BottomPopup(this))
                        .show();
                break;
        }
    }

    private void downVideo() {
        if (!StringUtils.isEmpty(videoUrl)) {
            String fileName = videoUrl.substring(videoUrl.lastIndexOf('/') + 1, videoUrl.length());
            String filePath = savePath + "/" + fileName;
            if (FileUtils.isFileExists(filePath)) {
                //如果文件存在，给出相应的提示
                com.blankj.utilcode.util.ToastUtils.showLong(getResources().getString(R.string.text_already_download));
                return;
            }
        }

        try {
            GetRequest<File> request = OkGo.<File>get(videoUrl);
            downloadTask = OkDownload.request(videoUrl, request);
            downloadTask.folder(savePath);
            downloadTask.register(new DownloadListener(videoUrl) {
                @Override
                public void onStart(Progress progress) {
                    showDownLoadDialog();
                    //howLoadingDialog("下载中...");
                }

                @Override
                public void onProgress(Progress progress) {

                }

                @Override
                public void onError(Progress progress) {
                    hideDownLoadDialog();
                    ToastUtils.showLong(getResources().getString(R.string.text_download_fail));
                }

                @Override
                public void onFinish(File file, Progress progress) {
                    //扫描更新媒体库(图库相册)
                    hideDownLoadDialog();
//                    MediaScannerConnection.scanFile(context, new String[]{savePath}, null, null);
                    new PictureMediaScannerConnection(context, file.getAbsolutePath(), () -> {
                    });

                    ToastUtils.showLong(getResources().getString(R.string.text_download_success));
                }

                @Override
                public void onRemove(Progress progress) {

                }
            });
            downloadTask.save();
            downloadTask.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 播放视频
     */
    private void playVideo(List<GSYVideoModel> urls, int position) {
        List<VideoOptionModel> list = new ArrayList<>();
        VideoOptionModel videoOptionMode0l = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "rtsp_transport", "tcp");
        VideoOptionModel videoOptionMode02 = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 0); //硬解码关闭
        VideoOptionModel videoOptionMode04 = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", 0);//是否开启缓冲
        list.add(videoOptionMode04);
        list.add(videoOptionMode0l);
        list.add(videoOptionMode02);
        GSYVideoManager.instance().setOptionModelList(list);
        resolveNormalVideoUI();
        //外部辅助的旋转，帮助全屏
        orientationUtils = new OrientationUtils(this, videoPlayer);
        //初始化不打开外部的旋转
        orientationUtils.setEnable(false);

        /**仅仅横屏旋转，不变直*/
        //orientationUtils.setOnlyRotateLand(true);

        Map<String, String> header = new HashMap<>();
//        header.put("ee", "33");
//        header.put("allowCrossProtocolRedirects", "true");
//        header.put("User-Agent", "GSY");
//        GSYVideoOptionBuilder gsyVideoOption = new GSYVideoOptionBuilder();
//        gsyVideoOption
//                .setIsTouchWiget(true)
//                .setRotateViewAuto(false)
//                //仅仅横屏旋转，不变直
//                .setOnlyRotateLand(true)
//
//                .setLockLand(false)
//                .setAutoFullWithSize(false)
//                .setShowFullAnimation(true)
//                .setNeedLockFull(false)
////                .setUrl(videoUrl)
//////                .setMapHeadData(header)
////                .setCacheWithPlay(false)
////                .setVideoTitle(title)
//                .setVideoAllCallBack(gsySampleCallBack)
//                .setLockClickListener(new MyLockClickListener())
//                .setGSYVideoProgressListener(new MyGSYVideoProgressListener())
//                .build(videoPlayer);
        videoPlayer.setIsTouchWiget(true);
        videoPlayer.setRotateViewAuto(false);
        videoPlayer.setOnlyRotateLand(true);
        videoPlayer.setAutoFullWithSize(false);
        videoPlayer.setShowFullAnimation(true);
        videoPlayer.setNeedLockFull(false);
        videoPlayer.setVideoAllCallBack(gsySampleCallBack);
        videoPlayer.setLockClickListener(new MyLockClickListener());
        videoPlayer.setGSYVideoProgressListener(new MyGSYVideoProgressListener());
        videoPlayer.setUp(urls, true, position);
        videoPlayer.startPlayLogic();//进来立即播放
    }

    private GSYSampleCallBack gsySampleCallBack = new GSYSampleCallBack() {
        @Override
        public void onPrepared(String url, Object... objects) {
            MyLogUtil.e(TAG, url + "***** onPrepared **** " + objects[0]);
            MyLogUtil.e(TAG, url + "***** onPrepared **** " + objects[1]);
            super.onPrepared(url, objects);
            //开始播放了才能旋转和全屏
            orientationUtils.setEnable(true);
            isPlay = true;

            //设置 seek 的临近帧。
            if (videoPlayer.getGSYVideoManager().getPlayer() instanceof Exo2PlayerManager) {
                ((Exo2PlayerManager) videoPlayer.getGSYVideoManager().getPlayer()).setSeekParameter(SeekParameters.NEXT_SYNC);
                MyLogUtil.e(TAG, "***** setSeekParameter **** ");
            }

            if (arrayUrl != null) {
                if (arrayUrl.length > 0) {
                    position = Arrays.binarySearch(arrayUrl, url); //根据元素查找位置索引
                    if (videoSubAdapter != null) {
                        videoSubAdapter.upData(position);
                    }
                }
            }

        }

        @Override
        public void onEnterFullscreen(String url, Object... objects) {
            super.onEnterFullscreen(url, objects);
            MyLogUtil.e(TAG, "***** onEnterFullscreen **** " + objects[0]);//title
            MyLogUtil.e(TAG, "***** onEnterFullscreen **** " + objects[1]);//当前全屏player
        }

        @Override
        public void onAutoComplete(String url, Object... objects) {
            super.onAutoComplete(url, objects);
            GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_4_3);
        }

        @Override
        public void onClickStartError(String url, Object... objects) {
            super.onClickStartError(url, objects);
        }

        @Override
        public void onQuitFullscreen(String url, Object... objects) {
            super.onQuitFullscreen(url, objects);
            MyLogUtil.e(TAG, "***** onQuitFullscreen **** " + objects[0]);//title
            MyLogUtil.e(TAG, "***** onQuitFullscreen **** " + objects[1]);//当前非全屏player
            if (orientationUtils != null) {
                orientationUtils.backToProtVideo();
            }
        }
    };

    private class MyLockClickListener implements LockClickListener {

        @Override
        public void onClick(View view, boolean lock) {
            if (orientationUtils != null) {
                //配合下方的onConfigurationChanged
                orientationUtils.setEnable(!lock);
            }
        }
    }

    private class MyGSYVideoProgressListener implements GSYVideoProgressListener {

        @Override
        public void onProgress(long progress, long secProgress, long currentPosition, long duration) {
            MyLogUtil.e(TAG, " progress " + progress + " secProgress " + secProgress + " currentPosition " + currentPosition + " duration " + duration);

        }
    }

    private class FullScreenOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            //直接横屏
            orientationUtils.resolveByClick();
            //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
            videoPlayer.startWindowFullscreen(VideoPlayActivity.this, false, false);
        }
    }


    private GSYVideoPlayer getCurPlay() {
        if (videoPlayer.getFullWindowPlayer() != null) {
            return videoPlayer.getFullWindowPlayer();
        }
        return videoPlayer;
    }

    private void resolveNormalVideoUI() {
        //增加title
        videoPlayer.getTitleTextView().setVisibility(View.GONE);
        videoPlayer.getBackButton().setVisibility(View.GONE);
    }

    /**
     * 底部弹出的pop
     */
    private class BottomPopup extends BottomPopupView {
        public VerticalRecyclerView recyclerView;

        public BottomPopup(@NonNull Context context) {
            super(context);

        }

        @Override
        protected int getImplLayoutId() {
            return R.layout.video_bottom_popup;
        }

        @Override
        protected void onCreate() {
            super.onCreate();
            recyclerView = findViewById(R.id.recyclerView);
            LinearLayoutManager manager = new LinearLayoutManager(context);
            recyclerView.setLayoutManager(manager);
            recyclerView.addItemDecoration(MyUtills.getRecyclerViewDivider(context, R.drawable.shape_dive_line));
            videoSubAdapter = new VideoSubAdapter(context, numberList, position);
            recyclerView.setAdapter(videoSubAdapter);
            videoSubAdapter.setOnItemClickListener(new VideoSubAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int p) {
                    if (arrayUrl != null) {
                        position = p;
                        playVideo(urls, position);
                    }
                }
            });
        }

        @Override
        protected void onShow() {
            super.onShow();
        }

        @Override
        protected void onDismiss() {
        }

        @Override
        protected int getMaxHeight() {
            return (int) (XPopupUtils.getScreenHeight(getContext()) * .7f);
        }
    }
}